<?php

namespace App\Http\Controllers\Admin\Service;

use App\Exports\OfficeExport;
use App\Exports\ProblemExport;
use App\Http\Controllers\Admin\Examine\Record;
use App\Http\Controllers\Controller;
use App\Http\Requests\service\ProblemRequest;
use App\Models\OrderModel;
use App\Models\service\AbnormalModel;
use App\Models\service\CompensateModel;
use App\Models\service\ProblemModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Problem extends Controller
{
    use ProblemRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $order_sn = $request->input('order_sn', '');
        $status = $request->input('status', '');
        $type_id = $request->input('type_id', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = ProblemModel::query()->with(['type', 'pro_admin', 'end_admin'])->withWhereHas('order', function ($query) use ($order_sn) {
            if($order_sn) {
                $query->with(['customer', 'take_order'])->where('sn', $order_sn);
            }else{
                $query->with(['customer', 'take_order']);
            }
        });

        if($status){
            $query = $query->where('status', $status);
        }

        if($type_id){
            $query = $query->where('type_id', $type_id);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'customer_name' => $item->order->customer ? $item->order->customer->name : '',
                'order_sn' => $item->order ? $item->order->sn : '',
                'take_order_sn' => $item->order->take_order ? $item->order->take_order->sn : '',
                'number' => $item->number,
                'weight' => $item->weight,
                'description' => $item->description,
                'type_name' => $item->type ? $item->type->name : '',
                'status' => $item->status,
                'status_text' => ProblemModel::STATUS[$item->status],
                'customer_reply' => $item->customer_reply,
                'programme' => $item->programme ?? '',
                'programme_name' => $item->programme ? ProblemModel::PROGRAMME[$item->programme] : '',
                'remarks' => $item->remarks,
                'pro_admin_user' => $item->pro_admin ? $item->pro_admin->name : '',
                'end_admin_user' => $item->end_admin ? $item->end_admin->name : '',
                'created_at' => $item->created_at->toDateTimeString(),
                'is_compensate' => $item->compensate_id ? 1 : 0,//是否发起过赔偿(1是，0否)
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * Notes:添加
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::add_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $find_order = OrderModel::where('sn', $params['order_sn'])->first();
        if(!$find_order){
            return $this->error('入仓号不存在');
        }

        if($params['number'] > $find_order->big_pkgs){
            return $this->error('件数不能大于入仓单大包件数');
        }

        //航班时间
        $take_order = TakeOrderModel::with('flight')->where('id', $find_order->take_order_id)->first();

        $flight_date = '';
        if($take_order && $take_order->flight && $take_order->flight->take_off_time){
            $flight_date = date('Y-m-d', strtotime($take_order->flight->take_off_time));
        }else{
            return $this->error('入仓单航班信息不存在');
        }

        DB::beginTransaction();
        try {

            $model = new ProblemModel();
            $model->order_id = $find_order->id;
            $model->customer_id = $find_order->customer_id;
            $model->type_id = $params['type_id'];
            $model->number = $params['number'];
            $model->weight = $params['weight'];
            $model->description = $params['description'] ?? '';
            $model->flight_date = $flight_date;
            $model->created_admin_id = $auth->id;
            $model->save();

            $find_order->is_issue = 1;
            $find_order->save();

            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:提供方案
     * User: xiangzi
     * Date: 2024/9/19
     * Time: 15:00
     * @return \Illuminate\Http\JsonResponse
     */
    public function programme(Request $request, $id)
    {
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::programme_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = ProblemModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $model->programme = $params['programme'];
        $model->pro_admin_id = $auth->id;
        $model->save();

        return $this->success();
    }

    /**
     * Notes:处理结案
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $model = ProblemModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $model->status = 3;
        $model->remarks = isset($params['remarks']) ? $params['remarks'] : '';
        $model->end_admin_id = $auth->id;
        $model->end_time = date('Y-m-d H:i:s');
        $model->save();

        return $this->success();
    }

    /**
     * Notes:发起赔偿
     * User: xiangzi
     * Date: 2024/9/19
     * Time: 17:52
     * @return \Illuminate\Http\JsonResponse
     */
    public function compensate(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::compensate_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = ProblemModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $order = OrderModel::find($model->order_id);

        DB::beginTransaction();
        try {

            $compensate = new CompensateModel();
            $compensate->customer_id = $model->customer_id;
            $compensate->order_id = $model->order_id;
            $compensate->take_order_id = $order->take_order_id;
            $compensate->amount = $params['amount'];
            $compensate->currency_id = $params['currency_id'];
            $compensate->pod_file = $params['pod_file'];
            $compensate->letter_file = $params['letter_file'];
            $compensate->lose_invoice = $params['lose_invoice'];
            $compensate->whole_invoice = $params['whole_invoice'];
            $compensate->lose_list = $params['lose_list'];
            $compensate->whole_list = $params['whole_list'];
            $compensate->remarks = $params['remarks'] ?? '';
            $compensate->pic_file = $params['pic_file'] ? json_encode($params['pic_file']) : '';
            $compensate->created_admin_id = $auth->id;
            $compensate->examine_record_id = (new Record())->add(2);
            $compensate->save();

            $model->compensate_id = $compensate->id;
            $model->compensate_time = date('Y-m-d H:i:s');
            $model->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:详情
     * User: xiangzi
     * Date: 2024/9/26
     * Time: 16:00
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        $id = intval($request->input('id', 0));
        $model = ProblemModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $data = ProblemModel::with(['type', 'customer'])->with('order', function ($query) {
            $query->with('take_order');
        })->find($id);

        $return = [
            'base_Info' => [
                'customer_name' => $data->customer->name ?? '',
                'order_sn' => $data->order->sn ?? '',
                'take_order_sn' => $data->order->take_order->take_order_sn ?? '',
                'number' => $data->number,
                'weight' => $data->weight,
                'type_name' => $data->type->name ?? '',
                'description' => $data->description ?? '',
                'status_text' => ProblemModel::STATUS[$data->status]
            ]
        ];

        if($data->compensate_id){
            $compensate = CompensateModel::find($data->compensate_id);
            if($compensate){
                $return['compensate_info'] = [
                    'compensate_time' => $compensate->created_at->toDateTimeString(),
                    'amount' => $compensate->amount,
                    'status_text' => CompensateModel::STATUS[$compensate->status] ?? '',
                    'remarks' => $compensate->remarks,
                    'letter_file' => $compensate->letter_file,
                    'pod_file' => $compensate->pod_file,
                    'lose_invoice' => $compensate->lose_invoice,
                    'whole_invoice' => $compensate->whole_invoice,
                    'lose_list' => $compensate->lose_list,
                    'whole_list' => $compensate->whole_list
                ];
            }else{
                $return['compensate_info'] = [];
            }
        }else{
            $return['compensate_info'] = [];
        }

        $return['handle_info'] = [];

        if($data->abnormal_id){
            $abnormal = AbnormalModel::find($data->abnormal_id);
            if($abnormal){
                $return['abnormal_info'][] = [
                    'time' => $abnormal->created_at->toDateTimeString(),
                    'desc' => '反馈异常'
                ];
            }
        }

        $return['handle_info'][] = [
            'time' => $data->created_at->toDateTimeString(),
            'desc' => '问题登记',
        ];

        if($data->customer_reply){
            $return['handle_info'][] = [
                'time' => $data->reply_time,
                'desc' => '客户回复' . "($data->customer_reply)"
            ];
        }

        if($data->compensate_time){
            $return['handle_info'][] = [
                'time' => $data->compensate_time,
                'desc' => '发起赔偿',
            ];
        }

        if($data->status == 3) {
            if($data->programme){
                $programme_mode = ProblemModel::PROGRAMME[$data->programme];
            }else{
                $programme_mode = '';
            }

            $return['handle_info'][] = [
                'time' => $data->end_time,
                'desc' => '已结案' . "($programme_mode)，" . $data->remarks
            ];
        }

        return $this->success($return);
    }

    /**
     * Notes:根据入仓号查询问题件
     * User: xiangzi
     * Date: 2024/9/29
     * Time: 17:16
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function check(Request $request)
    {
        $order_sn = $request->input('order_sn', '');
        $order = OrderModel::where('sn', $order_sn)->first();
        if(!$order){
            return $this->error('入仓号不存在');
        }

        $model = ProblemModel::where('order_id', $order->id)->first();
        if(!$model){
            return $this->success(['is_problem' => 0]);
        }

        if($model->programme){
            $programme = ProblemModel::PROGRAMME[$model->programme] ?? '';
        }else{
            $programme = '暂未提供处理方案';
        }

        return $this->success(['id' => $model->id, 'programme' => $programme, 'is_problem' => 1]);
    }

    /**
     * Notes:导出
     * User: xiangzi
     * Date: 2025/5/6
     * Time: 上午11:15
     * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = ProblemModel::query()->with(['type', 'order', 'customer']);
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'customer_name' => $item->customer->name ?? '',
                'order_sn' => $item->order ? $item->order->sn : '',
                'type' => $item->type->name ?? '',
                'number' => $item->number,
                'weight' => $item->weight,
                'description' => $item->description,
                'status' => ProblemModel::STATUS[$item->status],
                'created_at' => $item->created_at->toDateTimeString()
            ];
            return $res;
        });

        $file_name = '问题件列表-'.date('Ymd').'.xlsx';
        return Excel::download(new ProblemExport($list), $file_name);

    }


}
